import { _decorator, AudioSource, Component, director, Node } from 'cc';
import { BaseManager } from './BaseManager';
import { _item, _platform, _player, _resource, _storage, _tip, _wheel } from '../Main';
import { AudioName, NodeName } from './ResourceManager';
import { TT } from '../platforms/minis/TT';
import { BaseItem } from '../items/BaseItem';
const { ccclass, property } = _decorator;

@ccclass('PlayerManager')
export class PlayerManager extends BaseManager {

    managerName: string = '玩家管理器'

    settings = {
        music: 1,
        sound: 1,
        shake: 1
    }

    props = {

    }

    data = {
        lastLogin: 0,
        energy: 3,
        signDay: 1
    }

    daily = {
        daily: 1,
        sign: 1,
        success: 0,
    }

    bonuses = {
        sidebar: 1,
        shortcut: 1,
        favorite: 1
    }

    shopLimits = {
        
    }

    items = {

    }

    /** 音乐音频组件 */
    musicAudio: AudioSource = null

    /** 音效音频组件 */
    soundAudio: AudioSource = null

    sameDay: boolean = false

    init(): void {
        this.loadAll()
    }

    /** 加载 */
    loadAll() {
        this.loadAllSettings()
        this.loadNumData('lastLogin', this.data, 0)
        this.loadNumData('energy', this.data, 3)
        if (!_wheel.isTheSameDay(this.data.lastLogin)) {
            if (this.data.energy < 3) {
                this.changeNumData('energy', this.data, 3, 'set')
            }
            this.resetDaily()
            this.loadSign(false)
            this.sameDay = false
        } else {
            this.loadAllFrom(this.daily)
            this.loadSign(true)
            this.sameDay = true
        }
        this.loadAllFrom(this.bonuses)
        this.changeNumData('lastLogin', this.data, Date.now(), 'set')
    }

    /** 加载全部设置 */
    loadAllSettings() {
        this.loadSetting('music')
        this.loadSetting('sound')
        this.loadSetting('shake')
    }

    loadShopLimit(key: string) {
        if (!this.sameDay) {
            this.changeNumData(key, this.shopLimits, 2, 'set')
        } else {
            this.loadNumData(key, this.shopLimits, 2)
        }
    }

    /**
     * 加载设置
     * @param key 键
     * @returns 值
     */
    loadSetting(key: 'music' | 'sound' | 'shake'): number {
        let setting = _storage.getLocalItem(key)
        let num: number = setting ? Number(setting) : 1
        this.settings[key] = num
        return num
    }

    /** 重置每日 */
    resetDaily() {
        this.changeNumData('daily', this.daily, 1, 'set')
        this.changeNumData('success', this.daily, 0, 'set')
    }

    /**
     * 从一个{}中加载全部
     * @param from {}
     */
    loadAllFrom(from: {}) {
        for (let key in from) {
            this.loadNumData(key, from, 1)
        }
    }

    loadSign(sameDay: boolean) {
        this.loadNumData('signDay', this.data, 1)
        let sign: number = this.loadNumData('sign', this.daily, 1)
        if (!sameDay) {
            if (sign <= 0) {
                let next: number = this.data.signDay + 1 > 7 ? 1 : this.data.signDay + 1
                this.changeNumData('signDay', this.data, next, 'set')
            }
            this.changeNumData('sign', this.daily, 1, 'set')
        } else {
            this.loadNumData('sign', this.daily, 1)
        }
    }

    /** 创建音频节点，一般在场景切换后调用 */
    initAduios() {
        let audio = director.getScene().getChildByName('Audio')
        if (!audio) {
            audio = _resource.createNode(NodeName.AudioNode, director.getScene())
        }
        if (!audio) {
            console.log('音频节点加载错误')
            return
        }
        let music: Node = audio.getChildByName('Music')
        if (!music) {
            console.log('音频节点未包含名为"Music"的节点')
        } else {
            this.musicAudio = music.getComponent(AudioSource)
            this.switchBgm()
        }
        let sound: Node = audio.getChildByName('Sound')
        if (!sound) {
            console.log('音频节点未包含名为"Sound"的节点')
        } else {
            this.soundAudio = sound.getComponent(AudioSource)
        }
    }

    /**
     * 获取设置的值
     * @param key 键
     * @returns 值
     */
    getSetting(key: string): number {
        return this.settings[key]
    }

    /**
     * 改变设置
     * @param key 键
     * @param value 值
     * @param save 是否储存
     */
    changeSetting(key: string, value: number, save: boolean = true) {
        this.settings[key] = value
        if (save) {
            _storage.setLocalItem(key, value + '')
        }
        if (key === 'Music') {
            this.switchBgm()
        }
    }

    /** 播放音乐 */
    switchBgm(audioName?: AudioName) {
        if (!this.musicAudio) {
            return
        }
        if (this.settings.music != 1) {
            this.musicAudio.stop()
        } else {
            if (audioName) {
                if (this.musicAudio.playing) {
                    this.musicAudio.stop()
                }
                this.musicAudio.clip = _resource.getAudioClip(audioName)
            }
            this.musicAudio.play()
        }
    }

    /** 播放音效 */
    playSound(audioName: AudioName) {
        if (!this.soundAudio) {
            return
        }
        if (this.settings.sound != 1) {
            return
        }
        this.soundAudio.playOneShot(_resource.getAudioClip(audioName))
    }

    /**
     * 振动
     * @param type 振动类型
     */
    doShake(type: 'short' | 'long' = 'short') {
        if (this.settings.shake != 1) {
            return
        }
        _platform.platform.vibrate(type)
    }

    
    /**
     * 加载值为number的数据
     * @param key 键
     * @param from {}
     * @param defaultNum 取不到数据的默认值，默认为0
     * @returns 值
     */
    loadNumData(key: string, from: {}, defaultNum: number = 0): number {
        let data = _storage.getLocalItem(key)
        let num: number = data ? Number(data) : defaultNum
        from[key] = num
        return num
    }

    /**
     * 获取值为number的数据
     * @param key 键
     * @param from {}
     * @returns 值
     */
    getDataNum(key: string, from: {}, defaultNum: number = 0): number {
        let num = from[key]
        return num ? num : this.loadNumData(key, from, defaultNum)
    }

    /**
     * 改变值为number的数据
     * @param key 键
     * @param from {}
     * @param number 数值 
     * @param type 设置或增加
     * @param save 是否存储，默认为是
     * @param then 紧接着执行
     */
    changeNumData(key: string, from: {}, number: number, type: 'set' | 'add', save: boolean = true, then?: () => void) {
        let num: number = 0
        if (type == 'set') {
            num = number
        } else {
            let fkn = from[key]
            let n: number = fkn ? fkn : this.loadNumData(key, from)
            num = Math.max(0, (n + number))
        }
        from[key] = num
        if (save) {
            _storage.setLocalItem(key, num + '')
        }
        if (then) {
            then()
        }
    }
}


